import router from '@/router'

//@ts-ignore
import nprogress from 'nprogress'
//引入进度条样式
import 'nprogress/nprogress.css'
import { useUserStore } from './stores/modules/user'
import { GET_TOKEN } from './utils/token'

router.beforeEach(async (to, from, next) => {
  nprogress.start()
  const userStore = useUserStore()
  let token = userStore.token
  let username = await userStore.username
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (username) {
        next()
      } else {
        try {
          await userStore.userInfo()
          //放行
          //万一:刷新的时候是异步路由,有可能获取到用户信息、异步路由还没有加载完毕,出现空白的效果
          //所以执行next({...to})直到找到对应路由
          //replace设置，不能通过浏览器后退按钮，返回前一个路由
          next({ ...to, replace: true })
        } catch (error) {
          await userStore.userLogout()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    console.log(to.path, token)
    if (to.path === '/login') {
      console.log(to.path, token, username)
      next()
    } else {
      console.log(to.path, token, username)
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})

router.afterEach((to, from) => {
  nprogress.done()
})
